package com.dex4d.core;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.dex4d.dialog.LoadingManager;
import com.dex4d.utils.LocaleUtil;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by chengyuchun on 2018/10/17.
 */
public abstract class AppBaseActivity extends AppCompatActivity {
    protected ImmersionBar mImmersionBar;
    protected Unbinder mUnbinder;
    protected LoadingManager mLoadingManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getLayoutView() != null) {
            setContentView(getLayoutView());
        } else {
            setContentView(getLayoutId());
        }
        mUnbinder = ButterKnife.bind(this);//绑定View
        initImmersionBar();

        initVariables();
        loadData();
    }

    protected abstract int getLayoutId();

    protected View getLayoutView() {
        return null;
    }

    protected abstract void initVariables();

    protected abstract void loadData();

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
    }

    public void openActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void openActivity(Class<?> cls) {
        openActivity(cls, null);
    }

    public void openActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, cls);
        if (bundle != null)
            intent.putExtras(bundle);
        startActivityForResult(intent, requestCode);
    }

    public void openActivityForResult(Class<?> cls, int requestCode) {
        openActivityForResult(cls, null, requestCode);
    }

    public LoadingManager getLoadingManager() {
        if (null == mLoadingManager) {
            mLoadingManager = new LoadingManager(this);
        }
        return mLoadingManager;
    }

    public void showLoadingDialog() {
        getLoadingManager().showLoadingDialog();
    }

    public void dismissLoadingDialog() {
        if (mLoadingManager != null) {
            mLoadingManager.dismissLoadingDialog();
            mLoadingManager = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null)
            mUnbinder.unbind();//解绑View
        ImmersionBar.with(this).destroy();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleUtil.attachBaseContext(base));
    }
}
